//
//  NSDate+YTAdd.m
//  tesDemo02
//
//  Created by 拓客营 on 2022/3/21.
//

#import "NSDate+YTAdd.h"

@implementation NSDate (YTAdd)

/// 将日期字符串转换为默认格式的日期
/// @param dateString 日期字符串
+ (NSDate *)dateFromString:(NSString *)dateString {
    return [self dateFromString:dateString format:@"yyyy-MM-dd HH:mm:ss"];
}


/// 将日期字符串按指定格式转换为日期
/// @param dateString 日期字符串
/// @param format 格式化
+ (NSDate *)dateFromString:(NSString *)dateString format:(NSString *)format {
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = format;
    NSDate *date = [formatter dateFromString:dateString];
    NSAssert(![date isEqual:[NSNull null]], @"转换失败，检查格式跟字符串格式是否一致");
    return date;
}

/// 比较两个日期直接的差值(年月日时分秒)，结果为正数
/// @param date 日期
/// @param anotherDate 另一个日期
+ (NSDateComponents *)compareDate:(NSDate *)date anotherDate:(NSDate *)anotherDate {
    
    NSComparisonResult result = [date compare:anotherDate];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit =
    NSCalendarUnitYear|
    NSCalendarUnitMonth|
    NSCalendarUnitDay|
    NSCalendarUnitHour|
    NSCalendarUnitMinute|
    NSCalendarUnitSecond;
    
    if (result == NSOrderedAscending) {
        return [calendar components:unit fromDate:date toDate:anotherDate options:0];
    }
    
    return [calendar components:unit fromDate:anotherDate toDate:date options:0];
}

@end
